import threading


class AllConfig:
    """
    配置文件
    """

    def __init__(self, interval_seconds=5):
        self.interval_seconds = interval_seconds

    def set_interval_seconds(self, client):
        run_ts = client.get("run:config")
        if run_ts:
            run_ts = int(run_ts)
            self.interval_seconds = run_ts


class AlgoConfig:

    def __init__(self):
        self.map_config = {}
        self.map_config_lock = threading.Lock()

    def get_algo_configs(self, algo_name, same_algo=None):
        res = {}
        with self.map_config_lock:
            if same_algo and len(same_algo):
                for algo in same_algo:
                    res.update(self.map_config[algo])
            else:
                if self.map_config.__contains__(algo_name):
                    res.update(self.map_config[algo_name])
            return res

    def set_algo_configs(self, algo_name, configs):
        with self.map_config_lock:
            self.map_config[algo_name] = configs


class AlgoRunConfig:

    def __init__(self):
        self.stop_algo = []
        self.stop_algo_lock = threading.Lock()
        self.algo_router = {}
        self.algo_router_lock = threading.Lock()
        self.algo_load_model = {}
        self.algo_load_model_lock = threading.Lock()
        self.white_list_algo = []
        self.algo_type1 = []
        self.algo_type2 = []
        self.algo_type3 = []
        self.algo_combine_algo = {}

    def get_algo_router(self, algo_name):
        with self.algo_router_lock:
            return self.algo_router[algo_name]

    def get_stop_algo(self, algo_name):
        with self.stop_algo_lock:
            if algo_name in self.stop_algo:
                return True
            else:
                return False

    def set_stop_algo(self, algo_name, flag):
        with self.stop_algo_lock:
            if flag:
                self.stop_algo.append(algo_name)
            else:
                self.stop_algo.remove(algo_name)

    def need_to_load_model(self, algo_name):
        with self.algo_load_model_lock:
            if self.algo_load_model.__contains__(algo_name) and self.algo_load_model[algo_name]:
                return self.algo_load_model[algo_name]
            else:
                return False, False

    def set_need_to_load_model(self, algo_name, res):
        with self.algo_load_model_lock:
            self.algo_load_model[algo_name] = res

    def get_all_algo_list(self):
        algo_list = self.algo_type1 + self.algo_type3
        for k, v_list in self.algo_combine_algo.items():
            algo_list.append(v_list[0])
        return algo_list

    def get_same_algo(self, algo):
        for k, v_list in self.algo_combine_algo.items():
            for v in v_list:
                if v == algo:
                    return v_list
        return None
